<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="50%"
    title="新增"
    :footer="null"
    @cancel="handleCancel"
  >
    <div class="upload-container">
      <div class="upload-title">图片上传</div>
      <JImgUpload
        v-model:value="imageUrl"
        :url="uploadImage"
        :params="{ platform: 'tencent-cos-1' }"
      />
      <div v-if="imageUrl" class="upload-success">
        <a-icon type="check-circle" style="color: #52c41a; margin-right: 8px" />
        上传成功
      </div>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
  import { defineModel, ref, watch } from 'vue';
  import JImgUpload from '/@/components/JImgUpload/src/JImgUpload.vue';
  import { defHttp } from '@/utils/http/axios';
  import { ContentTypeEnum } from '@/enums/httpEnum';
  import { message } from 'ant-design-vue';

  const visible = defineModel('visible');
  const imageUrl = ref<string>('');
  const emit = defineEmits(['confirm']);

  // 监听弹窗关闭，重置状态
  watch(visible, (newVal) => {
    if (!newVal) {
      // 弹窗关闭时重置上传状态
      imageUrl.value = '';
    }
  });

  // 监听上传成功
  watch(imageUrl, (newUrl) => {
    if (newUrl && newUrl !== '') {
      // 上传成功，显示提示并关闭窗口
      message.success('文件上传成功！');
      setTimeout(() => {
        visible.value = false;
        // 触发父组件刷新列表
        emit('confirm');
      }, 1000); // 延迟1秒关闭，让用户看到成功提示
    }
  });

  // 处理弹窗取消
  const handleCancel = () => {
    imageUrl.value = '';
  };

  // 自定义上传方法，调用 SysFileStorageController 的 upload 接口
  const uploadImage = async (data: { file: File }, params: any) => {
    try {
      const formData = new FormData();
      formData.append('file', data.file);
      formData.append('platform', params.platform || 'local');

      const result = await defHttp.post(
        {
          url: '/system/file/upload',
          data: formData,
        },
        {
          contentType: ContentTypeEnum.BLOB,
          region: 'cloud-api',
        },
      );

      // 调试信息
      console.log('上传返回结果:', result);

      // 后端返回的是 InvokeResult<FileInfo>，前端接收的是 Result<T>
      // 数据在 result.data 中，FileInfo 对象包含 url 属性
      if (result && result.url) {
        console.log('获取到文件URL:', result.url);
        return result.url;
      } else {
        console.error('未获取到文件URL，result:', result);
        throw new Error('上传失败：未获取到文件URL');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      message.error('文件上传失败，请重试！');
      throw error;
    }
  };
</script>

<style scoped>
  .upload-container {
    padding: 16px;
  }

  .upload-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: #333;
  }

  .upload-success {
    margin-top: 16px;
    padding: 8px 12px;
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 4px;
    color: #52c41a;
    display: flex;
    align-items: center;
  }
</style>
